<!DOCTYPE html>
<html lang="zh-cn">
  <head>
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"
    />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <title>4. 寻找两个正序数组的中位数</title>
  </head>
  <body>
    <!-- start -->
    <div>https://leetcode.cn/problems/median-of-two-sorted-arrays/</div>
    <!-- end -->
  </body>
  <!-- js start -->
  <script type="text/javascript">
    /**
     * @param {number[]} nums1
     * @param {number[]} nums2
     * @return {number}
     */
    var findMedianSortedArrays = function (nums1, nums2) {
      if (nums1.length === 0) return countArrayVal(nums2);
      if (nums2.length === 0) return countArrayVal(nums1);

      const newArr = [...nums1, ...nums2].sort((a, b) => a - b);

      return countArrayVal(newArr);
    };

    /** 通过数组长度获取中位数索引 */
    function findMedianIndexArr(len) {
      if (len % 2 === 0) {
        const target = len / 2;
        return [target - 1, target + 1 - 1];
      } else {
        return [(len + 1) / 2 - 1];
      }
    }

    /** 计算单个数组中位数 */
    function countArrayVal(arr = []) {
      let indexArr = findMedianIndexArr(arr.length);

      let valArr = indexArr.map((item) => {
        return arr[item];
      });

      if (valArr.length === 1) return valArr[0];

      return (
        valArr.reduce((prev, curr) => {
          return prev + curr;
        }) / valArr.length
      );
    }

    console.log(findMedianSortedArrays([1, 3], [2]));
  </script>
</html>
